package cn.schoolwow.workflow.module.common.handler;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.listener.TryCatchFinallyHandler;

public class TransactionTryCatchFinallyHandler implements TryCatchFinallyHandler {

    @Override
    public void handleTryStart(FlowContext flowContext) throws Exception {
        if(!flowContext.containKey("transaction")){
            flowContext.putData("开启事务流程", flowContext.getFlowName());

            DAO dao = flowContext.checkInstanceData(DAO.class);
            Transaction transaction = dao.startTransaction();
            flowContext.putInstanceData(transaction, Transaction.class);
        }
    }

    @Override
    public void handleTryEnd(FlowContext flowContext) throws Exception {

    }

    @Override
    public void handleException(FlowContext flowContext, Exception e) {
        e.printStackTrace();
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);
        transaction.rollback();
    }

    @Override
    public void handleFinally(FlowContext flowContext) {
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);
        if(null==flowContext.getFlowException()){
            transaction.commit();
        }

        String startTransactionFlowName = (String) flowContext.checkData("开启事务流程");
        if(startTransactionFlowName.equals(flowContext.getFlowName())){
            transaction.close();
            flowContext.removeData("transaction");
        }
    }

    @Override
    public String name() {
        return "数据库事务操作处理前后处理器";
    }
}
